package com.liuhuanss.idCard.util;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Http Client 工具类
 */
@Component
public class HttpUtil {
	/**
	 * 发送post请求，根据 Content-Type 返回不同的返回值
	 * 
	 * @param url
	 * @param header
	 * @param body
	 * @return
	 */
	public static String doPost2(String url, Map<String, String> header, String body) {
		HttpURLConnection conn = null;
		PrintWriter out = null;
		BufferedReader in = null;

		try {
			// 创建URL对象
			URL realUrl = new URL(url);
			conn = (HttpURLConnection) realUrl.openConnection();

			// 设置连接超时和读取超时
			conn.setConnectTimeout(15000); // 15秒连接超时
			conn.setReadTimeout(60000);     // 60秒读取超时

			// 设置请求方法
			conn.setRequestMethod("POST");

			// 设置请求头
			for (Map.Entry<String, String> entry : header.entrySet()) {
				conn.setRequestProperty(entry.getKey(), entry.getValue());
			}

			// 允许输出输入
			conn.setDoOutput(true);
			conn.setDoInput(true);

			// 发送请求体
			out = new PrintWriter(conn.getOutputStream());
			out.print(body);
			out.flush();

			// 检查HTTP响应状态
			int responseCode = conn.getResponseCode();
			if (responseCode != HttpURLConnection.HTTP_OK) {
				// 读取错误流
				try (BufferedReader errorReader = new BufferedReader(
						new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
					StringBuilder errorResponse = new StringBuilder();
					String errorLine;
					while ((errorLine = errorReader.readLine()) != null) {
						errorResponse.append(errorLine);
					}
					throw new IOException("HTTP error " + responseCode + ": " + errorResponse.toString());
				}
			}

			// 读取响应体（使用UTF-8字符集）
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
			StringBuilder response = new StringBuilder();
			String line;
			while ((line = in.readLine()) != null) {
				response.append(line);
			}

			return response.toString();
		} catch (Exception e) {
			throw new RuntimeException("HTTP request failed: " + e.getMessage(), e);
		} finally {
			// 确保资源被关闭
			try {
				if (out != null) out.close();
				if (in != null) in.close();
				if (conn != null) conn.disconnect();
			} catch (Exception e) {
				// 忽略关闭时的异常
			}
		}
	}
	/**
	 * 发送post请求
	 * 
	 * @param url
	 * @param header
	 * @param body
	 * @return
	 */
	public static String doPost1(String url, Map<String, String> header, String body) {
		String result = "";
		BufferedReader in = null;
		PrintWriter out = null;
		try {
			// 设置 url
			URL realUrl = new URL(url);
			URLConnection connection = realUrl.openConnection();
			HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
			// 设置 header
			for (String key : header.keySet()) {
				httpURLConnection.setRequestProperty(key, header.get(key));
			}
			// 设置请求 body
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			out = new PrintWriter(httpURLConnection.getOutputStream());
			// 保存body
			out.print(body);
			// 发送body
			out.flush();
			if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) {
				System.out.println("Http 请求失败，状态码：" + httpURLConnection.getResponseCode());
				return null;
			}

			// 获取响应body
			in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			return null;
		}
		return result;
	}

	/**
	 * 流转二进制数组
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	private static byte[] toByteArray(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}
}
